package com.whty.ssm.db01.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Copyright 2016-2022 tianyu education Corporation, All Rights Reserved
 * http://www.whty.com.cn/
 *
 * @author wangming
 * @version 1.0
 * @date 2020/9/1 19:50
 * @since 1.0
 */

@Controller
public class StudentController {
    private final static Logger log = LoggerFactory.getLogger(StudentController.class);
    @Autowired
    public com.whty.ssm.db01.service.StudentService studentService;
//    http://localhost:8080/myssm/getOneStuById?id=10002
    @RequestMapping("/getOneStuById")
    @ResponseBody
    public com.whty.ssm.db01.pojo.Student getOneStuById(@RequestParam String id){
        com.whty.ssm.db01.pojo.Student student = studentService.getStudentById(id);
        return student;
    }
    @RequestMapping("/getOneStuById1")
    public void getOneStuById1(HttpServletResponse response, @RequestParam String id){
        com.whty.ssm.db01.pojo.Student student = studentService.getStudentById(id);
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(student));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    只有 student才是json 而 pageNum pageSize 只能 类似get传参了；
    http://localhost:8080/myssm/getManyStudents?pageNum=1&pageSize=100
    {
        "id": "1194872",
            "name": "丁一克",
            "age": "119",
            "phone": "15622911105",
            "pageNum": "1",
            "pageSize": "10"
    }
    */
    @RequestMapping(value = "/getManyStudents",method={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Object getManyStudents(@RequestBody com.whty.ssm.db01.pojo.Student student, Integer pageNum, Integer pageSize){
        log.info(student.toString()+" Integer pageNum,Integer pageSize --> "+pageNum+"-"+pageSize);
        pageNum = ( null == pageNum || pageNum <= 0 ) ? 1 : pageNum;
        pageSize = ( null == pageSize || pageSize <= 0 ) ? 1 : pageSize;

        PageHelper.startPage(pageNum,pageSize);
        List<com.whty.ssm.db01.pojo.Student> manyStudents = studentService.getManyStudents(student);
        PageInfo<com.whty.ssm.db01.pojo.Student> pageInfo = new PageInfo<>(manyStudents);

        return pageInfo;
    }

}
